<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html lang="zh-CN">
<%
	pageContext.setAttribute("rootPath", request.getContextPath());
%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<head>
<title>雇员信息</title>
<link
	href="${rootPath}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css"
	rel="stylesheet">
<script src="${rootPath}/static/js/jquery-1.12.4.js"></script>
<script
	src="${rootPath}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>

	<!-- 员工添加模态框：点击新增按钮弹出对话框 -->
	<div class="modal fade" id="addEmployeeModal" tabindex="-1"
		role="dialog" aria-labelledby="myModalLabel">
		<div class="modal-dialog" role="document">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"
						aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
					<h4 class="modal-title" id="myModalLabel">员工添加</h4>
				</div>
				<div class="modal-body">
					<form class="form-horizontal">
						<div class="form-group">
							<label class="col-sm-2 control-label">姓名</label>
							<div class="col-sm-10">
								<input type="text" name="empName" class="form-control"
									id="empNameInput"> <span class="help-block"></span>
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-2 control-label">性别</label>
							<div class="col-sm-10">
								<label class="radio-inline"> <input type="radio"
									name="gender" id="genderMaleRadio" value="M" checked="checked">
									男
								</label> <label class="radio-inline"> <input type="radio"
									name="gender" id="genderFemaleRadio" value="F"> 女
								</label>
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-2 control-label">邮箱</label>
							<div class="col-sm-10">
								<input type="text" name="email" class="form-control"
									id="emailInput" placeholder="email@163.com"> <span
									id="emailInputError" class="help-block"></span>
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-2 control-label">部门</label>
							<div class="col-sm-4">
								<!-- 提交部门id,通过ajax从数据库中获取部门 -->
								<select class="form-control" name="dId" id="selectDeptName">

								</select>
							</div>
						</div>
					</form>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" id="closeEmpbtn">关闭</button>
					<button type="button" class="btn btn-primary" id="saveEmpbtn">添加</button>
				</div>
			</div>
		</div>
	</div>

	<!-- 员工修改模态框：点击编辑按钮弹出对话框 -->
	<div class="modal fade" id="updateEmployeeModal" tabindex="-1"
		role="dialog" aria-labelledby="myModalLabel">
		<div class="modal-dialog" role="document">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"
						aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
					<h4 class="modal-title" id="myModalLabel">员工修改</h4>
				</div>
				<div class="modal-body">
					<form class="form-horizontal">
						<div class="form-group">
							<label class="col-sm-2 control-label">姓名</label>
							<div class="col-sm-10">
								<input type="text" name="empName" class="form-control"
									id="empNameUpdate"> <span class="help-block"></span>
								<!-- 							 <p class="form-control-static" id="empNameUpdate"></p>
 -->
							</div>
						</div>
						<div class="form-group" id="updateGenderDiv">
							<label class="col-sm-2 control-label">性别</label>
							<div class="col-sm-10">
								<label class="radio-inline"> <input type="radio"
									name="gender" id="genderMaleRadioUpdate" value="M"
									checked="checked"> 男
								</label> <label class="radio-inline"> <input type="radio"
									name="gender" id="genderFemaleRadioUpdate" value="F"> 女
								</label>
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-2 control-label">邮箱</label>
							<div class="col-sm-10">
								<input type="text" name="email" class="form-control"
									id="emailUpdate" placeholder="email@163.com"> <span
									id="emailUpdateError" class="help-block"></span>
							</div>
						</div>
						<div class="form-group" id="updateDeptNameDiv">
							<label class="col-sm-2 control-label">部门</label>
							<div class="col-sm-4">
								<!-- 提交部门id,通过ajax从数据库中获取部门 -->
								<select class="form-control" name="dId" id="selectDeptName">

								</select>
							</div>
						</div>
					</form>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" id="closeEmpbtn">关闭</button>
					<button type="button" class="btn btn-primary" id="updateEmpbtn">修改</button>
				</div>
			</div>
		</div>
	</div>

	<div class="container">
		<!-- 标题 -->
		<div class="row">
			<div class="col-md-12 text-center">
				<h1>雇员信息</h1>
			</div>
		</div>
		<!-- 按钮 -->
		<div class="row">
			<div class="col-md-4 col-md-offset-8">
				<button type="button" class="btn btn-info" id="addEmployeeBtn">
					<span class="glyphicon glyphicon-plus"></span> 添加
				</button>
				<button type="button" class="btn btn-danger" id="batchedDeleteBtn">
					<span class="glyphicon glyphicon-trash"></span> 删除
				</button>
			</div>
		</div>
		<!-- 显示表格内容 -->
		<div class="row">
			<div class="col-md-12">
				<table class="table table-hover" id="employeesInfoTable">
					<thead>
						<tr>
							<th><input type="checkbox" id="checkedAll" /></th>
							<th>编号</th>
							<th>姓名</th>
							<th>性别</th>
							<th>邮件</th>
							<th>部门</th>
							<th>操作</th>
						</tr>
					</thead>
					<tbody>

					</tbody>
				</table>
			</div>
		</div>

		<!-- 显示分页信息 -->
		<div class="row">
			<!-- 分页文字信息 -->
			<div class="col-md-6" id="pageNavigationInfo"></div>
			<!-- 分页条 -->
			<div class="col-md-6" id="pageNavigationBar"></div>
		</div>
	</div>

	<!-- 向服务器端发送ajax请求，返回分页数据 -->
	<script type="text/javascript">
		var totalRecord;//全局变量，假定总页数是很大值(总记录数肯定大于总页数)

		var currentPage;//全局变量，当前页

		$(function()
		{
			forwardPage(1);
		});

		//跳转到当前页面
		function forwardPage(pageNum)
		{
			$.ajax({
				url : "${rootPath}/employee/employees",
				data : "pageNum=" + pageNum,
				type : "GET",
				success : function(returnData)
				{
					//1.解析返回雇员信息
					getReturnDataWithEmpsInfo(returnData);

					//2.解析返回的分页数据，并添加到相应的div容器中
					getReturnDataWithPagerInfo(returnData);

					//3.解析返回的分页条信息，并添加到相应的div容器中
					getReturnDataWithPagerBar(returnData)
				}
			});
		}

		//获取返回雇员信息
		function getReturnDataWithEmpsInfo(returnData)
		{

			//清空缓存信息
			$("#employeesInfoTable tbody").empty();

			var employees = returnData.jsonMessage.pageInfo.list;

			$
					.each(
							employees,
							function(index, employee)
							{
								//console.log(index + "=", employee)
								//生成复选框
								var strCheckBox = $("<td><input type='checkbox' class='checkedItem'/></td>");
								//获取每一个雇员信息
								var strEmpId = $("<td></td>").append(
										employee.empId);
								var strEmpName = $("<td></td>").append(
										employee.empName);
								var strGender = $("<td></td>").append(
										employee.gender == 'M' ? '男' : '女');
								var strEmail = $("<td></td>").append(
										employee.email);
								var strDept = $("<td></td>").append(
										employee.department.deptName);

								//构建每一行的编辑按钮
								var editBtn = $("<button></button>")
										.addClass(
												"btn btn-primary btn-sm edit-btn")
										.append(
												$("<span></span>")
														.addClass(
																"glyphicon glyphicon-pencil"))
										.append("编辑");

								//添加编辑按钮自定义属性，以获取雇员Id
								editBtn.attr("edit_emp_id", employee.empId);

								//构建每一行的删除按钮
								var deleteBtn = $("<button></button>")
										.addClass(
												"btn btn-warning btn-sm delete-btn")
										.append(
												$("<span></span>")
														.addClass(
																"glyphicon glyphicon-remove"))
										.append("删除");

								//为删除按钮添加自定义属性，以获取雇员id
								deleteBtn.attr("delete_emp_id", employee.empId);

								//把编辑和删除按钮添加到操作单元格中
								var strOper = $("<td></td>").append(editBtn)
										.append(" ").append(deleteBtn);

								//添加每一行雇员信息到雇员表格中
								$("<tr></tr>").append(strCheckBox).append(
										strEmpId).append(strEmpName).append(
										strGender).append(strEmail).append(
										strDept).append(strOper).appendTo(
										"#employeesInfoTable tbody");
							});
		}

		//获取分页信息
		function getReturnDataWithPagerInfo(returnData)
		{

			//清空缓存页面信息
			$("#pageNavigationInfo").empty();

			//页面导航信息
			var pageNavigationInfo = returnData.jsonMessage.pageInfo;
			//把获取到的页面导航信息添加到id=pageNavigationInfo的div中
			$("#pageNavigationInfo").append(
					"当前是第 " + pageNavigationInfo.pageNum + " 页，总共 "
							+ pageNavigationInfo.pages + " 页，共有 "
							+ pageNavigationInfo.total + " 记录");

			//为全局变量totalRecord赋值
			totalRecord = pageNavigationInfo.total;

			//为全局变量currentPage赋值
			currentPage = pageNavigationInfo.pageNum;
		}

		//获取分页导航条信息
		function getReturnDataWithPagerBar(returnData)
		{
			//清空缓存分页条信息
			$("#pageNavigationBar").empty();

			var strUl = $("<ul></ul>").addClass("pagination");

			//首页
			var firstPageList = $("<li></li>")
					.append($("<a></a>").append("首页"));
			//上一页
			var prePageList = $("<li></li>").append(
					$("<a></a>").append("&laquo;"));

			//如果没有上一页，则上一页和首页禁止单击
			if (returnData.jsonMessage.pageInfo.hasPreviousPage == false)
			{
				firstPageList.addClass("disabled");

				prePageList.addClass("disabled");
			}
			else
			{
				//为首页添加单击事件
				firstPageList.click(function()
				{
					forwardPage(1);
				});

				//为上一页添加单击事件
				prePageList.click(function()
				{
					forwardPage(returnData.jsonMessage.pageInfo.pageNum - 1);
				});
			}

			//下一页
			var nextPageList = $("<li></li>").append(
					$("<a></a>").append("&raquo;"));
			//尾页
			var lastPageList = $("<li></li>").append($("<a></a>").append("尾页"));

			//如果没有下一页，则下一页和尾页禁止单击
			if (returnData.jsonMessage.pageInfo.hasNextPage == false)
			{
				nextPageList.addClass("disabled");

				lastPageList.addClass("disabled");
			}
			else
			{
				//为下一页添加单击事件
				nextPageList.click(function()
				{
					forwardPage(returnData.jsonMessage.pageInfo.pageNum + 1);
				});

				//为末页添加单击事件
				lastPageList.click(function()
				{
					forwardPage(returnData.jsonMessage.pageInfo.pages);
				});
			}

			//构造ul列表
			strUl.append(firstPageList).append(prePageList);

			$
					.each(
							returnData.jsonMessage.pageInfo.navigatepageNums,
							function(index, pageNumber)
							{
								var numList = $("<li></li>").append(
										$("<a></a>").append(pageNumber));

								//如果页码和当前页码相同，则高亮显示
								if (returnData.jsonMessage.pageInfo.pageNum == pageNumber)
								{
									numList.addClass("active");
								}

								//添加单击事件
								numList.click(function()
								{
									forwardPage(pageNumber);
								});

								strUl.append(numList);
							});

			strUl.append(nextPageList).append(lastPageList);

			//添加ul到导航元素中
			var navPageInfo = $("<nav></nav>").append(strUl);

			//把导航元素添加到分页条中
			navPageInfo.appendTo("#pageNavigationBar");
		}

		//绑定添加雇员按钮模态框事件
		$("#addEmployeeBtn").click(function()
		{
			//重置表单
			resetForm("#addEmployeeModal form");

			//弹出新增模态框之前发送ajax请求，查询部门信息
			queryDepartmentInfo("#addEmployeeModal select");

			$("#addEmployeeModal").modal({
				backdrop : "static"
			});
		});

		//查询部门信息
		function queryDepartmentInfo(deptNameSelectValue)
		{
			$(deptNameSelectValue).empty();

			//清空下拉列表的值
			$.ajax({
				url : "${rootPath}/department/departments",
				type : "GET",
				success : function(returnData)
				{
					//console.log(returnData);
					//在下拉列表获取部门信息
					//迭代部门信息
					$.each(returnData.jsonMessage.departments,
							function(index, department)
							{
								//获取option元素
								var optionElement = $("<option></option>")
										.append(department.deptName).attr(
												"value", department.deptId);
								//把获取到的元素添加到选择框中
								optionElement.appendTo(deptNameSelectValue);//
							});
				}
			});
		}

		//添加单击保存按钮事件
		$("#saveEmpbtn")
				.click(
						function()
						{

							//1.校验输入的数据合法后再保存
							/*if (!validateSaveEmployeeFormInfo())
							{
								return false;
							}*/

							//如果雇员名字已存在
							if ($(this).attr("ajax-validate") == "error")
							{
								return false;
							}

							//添加雇员信息请求
							$
									.ajax({
										url : "${rootPath}/employee/employee",
										type : "POST",
										data : $("#addEmployeeModal form")
												.serialize(),
										success : function(returnData)
										{
											/*
											1.显示保存雇员成功
											2.关闭保存模态框
											3.跳转到最后一页看到保存的雇员信息
											 */
											if (returnData.statusCode == 200)
											{
												//关闭保存模态框
												$("#addEmployeeModal").modal(
														"hide");
												//发送ajax请求跳转到最后一页看到保存的雇员信息
												//最后一页不确定可以假定是一个很大的页码，有mybatis分页插件的reasonable确定最后一页
												forwardPage(totalRecord);
											}
											else if (returnData.statusCode == 500)
											{
												//显示校验失败信息
												//有哪个字段的错误信息就获取哪个字段的错误信息

												if (undefined != returnData.jsonMessage.errors.empName)
												{
													//显示雇员名字的错误信息 
													showValidationInfo(
															"#empNameInput",
															"error",
															returnData.jsonMessage.errors.empName);
												}

												if (undefined != returnData.jsonMessage.errors.email)
												{
													//显示邮件错误信息 
													showValidationInfo(
															"#emailInput",
															"error",
															returnData.jsonMessage.errors.email);
												}
											}

										}
									});
						});

		//校验添加雇员信息模态框中的内容是否合法
		function validateSaveEmployeeFormInfo()
		{
			//校验雇员名字
			var empName = $("#empNameInput").val();
			var regName = /(^[a-zA-Z0-9_-]{5,16}$)|(^[\u2E80-\u9FFF]{2,5}$)/;

			if (!regName.test(empName))
			{
				//alert("雇员名字必须是6-12位字母和数字或者是2-6个中文字符");
				showValidationInfo("#empNameInput", "error",
						"雇员名字必须是6-12位字母和数字或者是2-6个中文字符")
				return false;
			}
			else
			{
				showValidationInfo("#empNameInput", "success", "")
			}

			//校验邮箱
			var email = $("#emailInput").val();
			var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;

			if (!regEmail.test(email))
			{
				//alert("邮箱格式不正确");
				showValidationInfo("#emailInput", "error", "邮箱格式不正确");
				return false;
			}
			else
			{
				showValidationInfo("#emailInput", "success", "");
			}

			return true;
		}

		//显示校验信息
		function showValidationInfo(validateElement, validateStatus,
									validateMessage)
		{
			//清除之前的状态
			$(validateElement).parent().removeClass("has-success has-error");
			$(validateElement).next("span").text("");

			//判断状态
			if (validateStatus == "success")
			{
				$(validateElement).parent().addClass("has-success");
				$(validateElement).next("span").text(validateMessage);
			}
			else if (validateStatus == "error")
			{
				$(validateElement).parent().addClass("has-error");
				$(validateElement).next("span").text(validateMessage);
			}

		}

		//为雇员姓名绑定改变事件，发送ajax请求验证用户名是否存在
		$("#empNameInput")
				.change(
						function()
						{
							$
									.ajax({
										url : "${rootPath}/employee/checkedEmpName",
										type : "GET",
										data : "empName="
												+ $("#empNameInput").val(),
										success : function(returnData)
										{
											if (returnData.statusCode == 200)
											{
												showValidationInfo(
														"#empNameInput",
														"success", "雇员名可用!");

												//为添加雇员模态框中的保存按钮添加ajax校验成功属性
												$("#saveEmpbtn").attr(
														"ajax-validate",
														"success");
											}
											else
											{
												showValidationInfo(
														"#empNameInput",
														"error",
														returnData.jsonMessage.validate_fail);

												//为添加雇员模态框中的保存按钮添加ajax校验失败属性
												$("#saveEmpbtn").attr(
														"ajax-validate",
														"error");
											}
										}
									});
						});

		//清空表单样式及内容
		function resetForm(formElement)
		{
			//在下次添加雇员之前清空模态框中的数据
			//jquery没有重置方法，需要使用dom中的reset()方法
			$(formElement)[0].reset();//$(formElement).get(0).reset();
			//清空表单样式
			$(formElement).find("*").removeClass("has-error has-success");
			//恢复表单最初状态
			$(formElement).find(".help-block").text("");
		}

		//点击编辑按钮，绑定单击事件(绑定不上，因为创建按钮之前绑定事件无效)
		//处理方式：(1)生成编辑按钮时绑定单击事件 (2)使用on()方法
		$(document).on(
				'click',
				".edit-btn",
				function()
				{
					//console.log("on...");

					//1.发送ajax请求，查出雇员信息
					queryEmployeeInfo($(this).attr("edit_emp_id"));

					//2.查询部门信息
					queryDepartmentInfo("#updateEmployeeModal select");

					//传递雇员id到相关的编辑按钮
					$("#updateEmpbtn").attr("edit_emp_id",
							$(this).attr("edit_emp_id"));

					//3.点击编辑按钮，弹出编辑模态框，把查询出来的部门信息和雇员信息填充到编辑框中
					$("#updateEmployeeModal").modal({
						backdrop : "static"
					});
				});

		function queryEmployeeInfo(empId)
		{
			$.ajax({
				url : "${rootPath}/employee/employee/" + empId,
				type : "GET",
				success : function(returnData)
				{
					//console.log(returnData);
					var empInfo = returnData.jsonMessage.employee;

					$("#empNameUpdate").val(empInfo.empName);

					$("#emailUpdate").val(empInfo.email);

					$("#updateGenderDiv input[name=gender]").val(
							[ empInfo.gender ]);

					$("#selectDeptName").val([ empInfo.dId ]);
				}
			});
		}

		//点击修改按钮事件
		$("#updateEmpbtn").click(
				function()
				{
					//1.校验修改的数据合法后再保存
					if (!validateUpdateEmployeeInfo())
					{
						return false;
					}

					//发送ajax请求更新雇员信息
					$.ajax({
						url : "${rootPath}/employee/employee/"
								+ $(this).attr("edit_emp_id"),
						type : "PUT",
						data : $("#updateEmployeeModal form").serialize(),
						success : function(resultData)
						{
							//console.log(resultData);

							$("#updateEmployeeModal").modal("hide");

							forwardPage(currentPage);
						}
					});

				});

		//修改雇员校验
		function validateUpdateEmployeeInfo()
		{
			//校验雇员名字
			var empName = $("#empNameUpdate").val();
			var regName = /(^[a-zA-Z0-9_-]{5,16}$)|(^[\u2E80-\u9FFF]{2,5}$)/;

			if (!regName.test(empName))
			{
				//alert("雇员名字必须是6-12位字母和数字或者是2-6个中文字符");
				showValidationInfo("#empNameUpdate", "error",
						"雇员名字必须是6-12位字母和数字或者是2-6个中文字符")
				return false;
			}
			else
			{
				showValidationInfo("#empNameUpdate", "success", "")
			}

			//校验邮箱
			var email = $("#emailUpdate").val();
			var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;

			if (!regEmail.test(email))
			{
				//alert("邮箱格式不正确");
				showValidationInfo("#emailUpdate", "error", "邮箱格式不正确");
				return false;
			}
			else
			{
				showValidationInfo("#emailUpdate", "success", "");
			}

			return true;
		}

		//为删除按钮绑定单击事件
		$(document).on('click', ".delete-btn", function()
		{
			//1.获取雇员姓名
			var empName = $(this).parents("tr").find("td").eq(2).text();

			//2.获取雇员id
			var empId = $(this).attr("delete_emp_id");

			if (window.confirm("确认删除 " + empName + " 吗？"))
			{
				$.ajax({
					url : "${rootPath}/employee/employee/" + empId,
					type : "DELETE",
					success : function()
					{
						forwardPage(currentPage);
					}
				});
			}
		});

		//选中全选复选框或取消全选复选框
		$("#checkedAll").click(function()
		{
			$(".checkedItem").prop("checked", $(this).prop("checked"));
		});

		//为选中的每个雇员复选框绑定单击事件
		$(document)
				.on(
						"click",
						".checkedItem",
						function()
						{

							var flag = $(".checkedItem:checked").length == $(".checkedItem").length;

							$("#checkedAll").prop("checked", flag);
						});

		//批量删除所选雇员记录
		$("#batchedDeleteBtn").click(
				function()
				{
					var empNames = "";

					var empIds = "";

					$.each($(".checkedItem:checked"), function()
					{
						empNames += $(this).parents("tr").find("td").eq(2)
								.text()
								+ ",";

						empIds += $(this).parents("tr").find("td").eq(1).text()
								+ "-";
					});

					empNames = empNames.substring(0, empNames.length - 1);

					empIds = empIds.substring(0, empIds.length - 1);

					if (confirm("确认删除 " + empNames + " 吗？"))
					{
						$.ajax({
							url : "${rootPath}/employee/employee/" + empIds,
							type : "DELETE",
							success : function()
							{
								forwardPage(currentPage);
							}
						});
					}
				});
	</script>
</body>
</html>